
from views import *

@managerrequired
def edit_coperativa(request, cope_id):
  """Create or edit a gift.  GET shows a blank form, POST processes it."""
  user = users.GetCurrentUser()
  if user is None:
    return http.HttpResponseForbidden('You must be signed in to add or edit a ')

  cope = None
  if cope_id:
    cope = Coperativa.get(db.Key.from_path(Coperativa.kind(), int(cope_id)))
    if cope is None:
      return http.HttpResponseNotFound('No coperativa exists with that key (%r)' %
                                       cope_id)

  form = CoperativaForm(data=request.POST or None, instance=cope)
  productes = db.GqlQuery('SELECT * FROM Product WHERE coperativa=:1', cope)
  if not request.POST:
    return respond(request, user, 'coperativa', {'form': form, 'cope': cope, 'productes':productes})

  errors = form.errors
  if not errors:
    try:
      cope = form.save(commit=False)
    except ValueError, err:
      errors['__all__'] = unicode(err)
  if errors:
    return respond(request, user, 'coperativa', {'form': form, 'cope': cope, 'productes':productes})

  #if not gift.giver:
  #  gift.giver = user
  cope.key_name=cope.name
  cope.save()

  return http.HttpResponseRedirect('/')

def new_coperativa(request):
  """Create a gift.  GET shows a blank form, POST processes it."""
  return edit_coperativa(request, None)
